package cn.yuemouren.security.core.social.qq.connect;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @Author: Timi
 * @Description: 自定义扩展模板
 * @Date: 2020/6/26 18:34
 * @Version: v1.0
 */
public class QQOAuth2Template extends OAuth2Template {

    private Logger logger = LoggerFactory.getLogger(getClass());

    public QQOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String accessTokenUrl) {
        super(clientId, clientSecret, authorizeUrl, accessTokenUrl);
        //设置拼装appid 和 secret
        setUseParametersForClientAuthentication(true);
    }

    /**
     * 加入处理text/html处理器
     * @return
     */
    @Override
    protected RestTemplate createRestTemplate() {
        RestTemplate template = super.createRestTemplate();
        List<HttpMessageConverter<?>> messageConverters = template.getMessageConverters();
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return template;
    }

    @Override
    protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
        String postForObject = getRestTemplate().postForObject(accessTokenUrl, parameters, String.class);
        logger.info("获取accessToken的响应为:"+postForObject);
        String[] params = StringUtils.split(postForObject, "&");
        String accessToken = StringUtils.substringAfter(params[0],"=");
        Long expireTime = Long.valueOf(StringUtils.substringAfter(params[1],"="));
        String refreshToken = StringUtils.substringAfter(params[2],"=");
        return new AccessGrant(accessToken,null,refreshToken,expireTime);
    }
}
